<?php
/* */
namespace app\api\service;

use app\api\model\Order as OrderModel;
use app\api\model\Product;
use app\api\service\Order as OrderService;
use app\lib\enum\OrderStatusEnum;
use Exception;
use think\Db;
use think\Log;

Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php');

class WxNotify extends \WxPayNotify{
    public function NotifyProcess($objData, $config, $msg)

        if($objData['result_code']=='SUCCESS'){
            $orderNo=$objData['out_trade_no'];
            Db::startTrans();
            try{
                $order=OrderModel::where('order_no','=',$orderNo)
                    ->lock(true)
                    ->find();
                if($order->status==1){
                    $service=new OrderService();
                    $stockstatus=$service->checkOrderStock($order->id);
                    if($stockstatus['pass']){
                        $this->updateOrderStatus($order->id,true);//更新订单状态
                        $this->reduceStock($stockstatus);//删减库存量
                        
                    }else{
                        $this->updateOrderStatus($order->id,false);
                    }
                }
                Db::commit();
                return true;
            }catch(Exception $ex)
            {
                Log::error($ex);
                return false;
            }
        }
    }

    private function reduceStock($stockstatus){
        foreach($stockstatus['pStatusArray']as $singlePStatus){
            Product::where('id','=',$singlePStatus['id'])
                ->setDec();
        }
    }

    private function updateOrderStatus($orderID,$success){
        $status=$success?
            OrderStatusEnum::PAID:
            OrderStatusEnum::PAID_BUT_OUT_OF;
            OrderModel::where('id','=',$orderID)
        ->updata(['status'=>$status]);
    }
}